<?php

/**
 *  获取商品价格
 */

namespace app\api\service;
use app\admin\service\BaseService;
use app\api\model\Customer;
use app\api\model\Warehouse;
use app\facade\Basic;
use app\admin\model\Inventory as InventoryModel;
use app\admin\model\ProductPrice as ProductPriceModel;
use PhpParser\Node\Expr\Isset_;
use think\facade\Db;

class ProductPrice extends BaseService
{
    /**
     *   获取 商品库存信息
     *   array $condition；
     *
     *   ===== 输入 =====
          * [
              * [
                  * 'productid' => '商品ID',
                  * 'wid' => '仓库',
                  * 'arrival_date' => Null,
                  * 'is_futures' => '0',
                  * 'quantity' => '0'
              * ]
          * ];
     *
     *    ===== 输出  =====
 */

    public function getPrice(array $condition)
    {
        /* 判空 */
        if ( empty($condition) ) {
            return Basic::data(1,'库存参数不存在');
        }


        try {
            $cartId = [];
            // 预处理键名和参数映射
            $cartKeys = array_map(function ($value) {
                return implode('_', [$value['productid'], $value['wid'], $value['arrival_date'], $value['is_futures']]);
            }, $condition);

            $cartIdMap = array_column($condition, 'id', 'cart_key');

            $productIds = array_column($condition, 'productid');
            foreach ($condition as $key => $value){
                $cart_key = implode('_', [
                    $value['productid'],
                    $value['wid'],
                    $value['arrival_date'],
                    $value['is_futures']
                ]);

                $cartId[$cart_key] = $value['id']??0;

                if (!is_numeric($value['productid'])) {
                    return Basic::data(1, 'KEY:'.$key.' productid 参数错误');
                }

                if (!is_numeric($value['wid'])) {
                    return Basic::data(1, 'KEY:'.$key.' wid 参数错误');
                }

                if (!in_array($value['is_futures'], [0,1,2])) {
                    return Basic::data(1, 'KEY:'.$key.' is_futures 参数错误');
                }

                if (!is_numeric($value['quantity']) ||  $value['quantity'] <= 0) {
                    return Basic::data(1, 'KEY:'.$key.' quantity 参数错误');
                }

                /* 购买数量 */
                $pay_quantity[implode('_', [
                    $value['productid'],
                    $value['wid'],
                    $value['arrival_date'],
                    $value['is_futures']
                ])] = $value['quantity'];

            }
            $inventory = InventoryModel::where('is_del', 0)->where('is_sale',1)
                ->whereIn('productid', $productIds)
                ->where(function ($query) use ($condition) {
                    foreach ($condition as $value) {
                        $query->whereOr(function ($q) use ($value) {
                            // 组合FIND_IN_SET与其他AND条件
                            $q->whereFindInSet('wid', $value['wid'])
                                ->where('productid', $value['productid'])
                                ->where('arrival_date', $value['arrival_date'])
                                ->where('is_futures', $value['is_futures'])
                                ->where(function ($sub) {
                                    $sub->where('available_qty', '>', 0)
                                        ->whereColumn('available_qty', '>', 'lock_qty')
                                        ->whereOr('allow_zero_stock_sale', 1); // 此处允许零库存销售
                                });
                        });
                    }
                })->select();
            if  ( !$inventory ) {
                return Basic::data(1,'未找到库存信息');
            }
            $inventoryData_base = $inventory->toArray();

            // 处理拆分 当wid是逗号隔开的情况 拆分成单独的数据
            $inventoryData = [];
            foreach ($inventoryData_base as $row) {
                $values = explode(',', $row['wid']);
                foreach ($values as $value) {
                    $newRow = $row;
                    $newRow['wid'] = trim($value);
                    $inventoryData[] = $newRow;
                }
            }
            /*  库存分组处理 */
            $groupedArray = [];
            $inventory_ids = [];
            foreach ($inventoryData as $item) {

                $key = implode('_', [
                    $item['productid'],
                    $item['wid'],
                    $item['arrival_date'],
                    $item['is_futures']
                ]);
                if (!isset($groupedArray[$key])) {
                    $groupedArray[$key] = [
                        'productid' => $item['productid'],
                        'wid' => $item['wid'],
                        'arrival_date' => $item['arrival_date'],
                        'real_arrival_date' => $item['real_arrival_date'],
                        'is_futures' => $item['is_futures'],
                        'inventory_id' => $item['id'],
                        'purchase_currency' => $item['purchase_currency'],
                        'purchase_price' => $item['purchase_price'],
                        'quantity' => $pay_quantity[$key]??0,
                    ];
                    $inventory_ids[] = $item['id'];
                } else {
                    continue;
                }

                unset($item['productid']);
                unset($item['wid']);
                unset($item['arrival_date']);
                unset($item['is_futures']);

            }

            //$data = array_values($groupedArray);

            /* 获取价格 */
            $product_price_where[] = ['transaction_currency_id','=','214'];
            $product_price_where[] = ['is_del','=','0'];
            $product_price_where[] = ['inventory_id','in',$inventory_ids];


            $RoductPrice = ProductPriceModel::with(['discount'=>function ($query) {
                $query->field('num,rate,price,price_id,level')->order('level ASC');
            }])->where($product_price_where)->field('id,inventory_id,wid,transaction_currency_id,price,first_leg_logistics_fee')
                ->select();

            if ( !$RoductPrice ) {
                return Basic::data(1,'未找到价格信息');
            }

            $RoductPrice = $RoductPrice->toArray();
            foreach ($RoductPrice as $key => $value) {
                $key = $value['inventory_id'].'_'.$value['wid'];
                $RoductPriceColumn[$key] = $value;
            }

            foreach ($groupedArray as $key => &$valuePrice) {
                $price_key = $valuePrice['inventory_id'].'_'.$valuePrice['wid'];
                if ( isset( $RoductPriceColumn[$price_key] ) ) {
                    $valuePrice['price'] = $RoductPriceColumn[$price_key];
                } else {
                    $valuePrice['price'] = [];
                }
            }

            $data = [];

            foreach ( $groupedArray as $key=>$item ) {
                # 只返回传入仓库的价格数据，共享仓库新增的数据过滤掉
                if(!isset($cartId[$key])){
                  continue;
                }
                $data[$key]['productid'] = $item['productid'];
                $data[$key]['cartId'] = $cartId[$key]??0;
                $data[$key]['wid'] = $item['wid'];
                $data[$key]['arrival_date'] = $item['arrival_date'];
                $data[$key]['real_arrival_date'] = $item['real_arrival_date'];
                $data[$key]['is_futures'] = $item['is_futures'];
                $data[$key]['quantity'] = $item['quantity'];
                $data[$key]['purchase_price'] = $item['purchase_price'];
                $data[$key]['purchase_currency'] = $item['purchase_currency'];

                if ( isset($item['price']) ) {
                    $discount_price = $this->getDiscountPrice($item['price']['discount'],$condition[0]['user_id'],$item['quantity']);
                    $data[$key]['price'] =$item['price']['price']??'';
                    $data[$key]['first_leg_logistics_fee'] =$item['price']['first_leg_logistics_fee']??'';
                    $data[$key]['sales_price'] = $discount_price ?: $item['price']['price'];
                } else {
                    $data[$key]['price'] = null;
                    $data[$key]['sales_price'] = null;

                }
            }

            return Basic::data(0,'common.success',$data);

        } catch (\Exception $e) {
            return Basic::data(1,$e->getMessage());
        }

    }
    public function getPriceNew(array $condition,$lang)
    {
        $common = new \app\api\service\Common();
        /* 判空 */
        if (empty($condition)) {
            return Basic::data(1, '库存参数不存在');
        }

        try {
            $cartId = [];
            $inputWarehouses = []; // 新增：记录每个商品组合的传入仓库信息 [修改]
            $productIds = array_column($condition, 'productid');

            foreach ($condition as $key => $value) {
                // 修改分组键格式（移除wid） [修改]
                $cart_key = implode('_', [
                    $value['productid'],
                    $value['arrival_date'],
                    $value['is_futures']
                ]);

                // 记录传入仓库信息 [修改]
                $wid = $value['wid'];
                $inputWarehouses[$cart_key][$wid] = [
                    'cartId' => $value['id'] ?? 0,
                    'quantity' => $value['quantity']
                ];

                if (!is_numeric($value['productid'])) {
                    return Basic::data(1, 'KEY:'.$key.' productid 参数错误');
                }

                if (!is_numeric($value['wid'])) {
                    return Basic::data(1, 'KEY:'.$key.' wid 参数错误');
                }

                if (!in_array($value['is_futures'], [0,1,2])) {
                    return Basic::data(1, 'KEY:'.$key.' is_futures 参数错误');
                }

                if (!is_numeric($value['quantity']) ||  $value['quantity'] <= 0) {
                    return Basic::data(1, 'KEY:'.$key.' quantity 参数错误');
                }
            }

            // 移除wid查询条件 [修改]
            $inventory = InventoryModel::where('is_del', 0)->where('is_sale',1)
                ->whereIn('productid', $productIds)
                ->where(function ($query) use ($condition) {
                    foreach ($condition as $value) {
                        $query->whereOr(function ($q) use ($value) {
                            $q->where('productid', $value['productid'])
                                ->where('arrival_date', $value['arrival_date'])
                                ->where('is_futures', $value['is_futures'])
                                ->where(function ($sub) {
                                    $sub->where('available_qty', '>', 0)
                                        ->whereColumn('available_qty', '>', 'lock_qty')
                                        ->whereOr('allow_zero_stock_sale', 1);
                                });
                        });
                    }
                })->select();

            if (!$inventory) {
                return Basic::data(1, '未找到库存信息');
            }
            $inventoryData_base = $inventory->toArray();

            // 处理拆分wid
            $inventoryData = [];
            $inventory_ids = [];
            foreach ($inventoryData_base as $row) {
                $values = explode(',', $row['wid']);
                foreach ($values as $value) {
                    $newRow = $row;
                    $newRow['wid'] = trim($value);
                    $inventoryData[] = $newRow;
                    $inventory_ids[] = $newRow['id']; // 收集库存ID
                }
            }

            // 重构分组逻辑（按产品+日期+期货分组） [修改]
            $groupedArray = [];
            $widss = [];
            $widss = array_column($inventoryData,'wid');
            $warehouse = Warehouse::where('id', 'in', $widss)->where('status',1)->field('id,pickup_address,support_selfpickup,name,show_name')->select()->toArray();
            $warehouse = array_column($warehouse,null,'id');
            foreach ($inventoryData as $item) {
                $key = implode('_', [
                    $item['productid'],
                    $item['arrival_date'],
                    $item['is_futures']
                ]);
                if (!isset($groupedArray[$key])) {
                    $groupedArray[$key] = [];
                }

                // 修改：以 wid 为键，确保每个仓库只保留一条数据 [新增修改]
                $wid = $item['wid'];
                $groupedArray[$key][$wid] = [
                    'wid' => $wid,
                    'inventory_id' => $item['id'],
                    'purchase_currency' => $item['purchase_currency'],
                    'purchase_price' => $item['purchase_price'],
                    'real_arrival_date' => $item['real_arrival_date']
                ];
            }

            // 获取价格
            $product_price_where[] = ['transaction_currency_id','=','214'];
            $product_price_where[] = ['is_del','=','0'];
            $product_price_where[] = ['inventory_id','in',$inventory_ids];

            $RoductPrice = ProductPriceModel::with(['discount'=>function ($query) {
                $query->field('num,rate,price,price_id,level')->order('level ASC');
            }])->where($product_price_where)->field('id,inventory_id,wid,transaction_currency_id,price,first_leg_logistics_fee')
                ->select();

            if (!$RoductPrice) {
                return Basic::data(1, '未找到价格信息');
            }

            $RoductPrice = $RoductPrice->toArray();
            $RoductPriceColumn = [];
            foreach ($RoductPrice as $value) {
                $key = $value['inventory_id'].'_'.$value['wid'];
                $RoductPriceColumn[$key] = $value;
            }

            // 重构返回数据结构 [修改]
            $data = [];
            foreach ($groupedArray as $key => $items) {
                list($productid, $arrival_date, $is_futures) = explode('_', $key);

                $data[$key] = [
                    'productid' => $productid,
                    'arrival_date' => $arrival_date === 'null' ? null : $arrival_date,
                    'is_futures' => $is_futures,
                    'warehouse_list' => []  // 存储多个仓库数据
                ];

                // 获取当前商品组合的传入仓库
                $inputWids = $inputWarehouses[$key] ?? [];

                // 修改：直接遍历 $items 的值（已通过 wid 去重） [新增修改]
                foreach ($items as $wid => $item) {
                    $inventory_id = $item['inventory_id'];

                    // 判断是否传入仓库 [修改]
                    $isDefault = isset($inputWids[$wid]) ? 1 : 0;
                    $quantity = $isDefault ? $inputWids[$wid]['quantity'] : 0;

                    $price_key = $inventory_id . '_' . $wid;
                    $priceData = $RoductPriceColumn[$price_key] ?? null;
                    if(!isset($warehouse[$wid])){
                        continue;
                    }
                    $name = $warehouse[$wid]['name'] ?? '';
                    $show_name = $warehouse[$wid]['show_name'] ?? '';
                    $warehouseData = [
                        'wid' => $wid,
                        'is_default' => $isDefault,
                        'name' => $common->singleTranslate($name,$lang),
                        'support_selfpickup' => $warehouse[$wid]['support_selfpickup'] ?? 0,
                        'pickup_address' => $warehouse[$wid]['pickup_address'] ?? '',
                        'show_name' => $common->singleTranslate($show_name,$lang),
                    ];

                    if ($priceData) {
                        $discount_price = $this->getDiscountPrice($priceData['discount'], $condition[0]['user_id'], $quantity);
                        $warehouseData['price'] = $priceData['price'] ?? '';
                        $warehouseData['sales_price'] = $discount_price ?: $priceData['price'];
                    } else {
                        $warehouseData['price'] = null;
                        $warehouseData['sales_price'] = null;
                    }
                    $data[$key]['warehouse_list'][] = $warehouseData;
                }
            }

            return Basic::data(0, 'common.success', $data);

        } catch (\Exception $e) {
            return Basic::data(1, $e->getMessage());
        }
    }

    /**
     * @param $price
     * @param $quantity
     * @param $discount
     * @param $user_id
     * @return mixed
     * 根据产品数量 和用户等级 获取商品价格
     */
    public function getDiscountPrice($discount, $user_id, $quantity)
    {
        $price = 0;
        if (!empty($discount)) {
            #获取最大折扣价格
            foreach ($discount as $d) {
                if ($d['level'] == 1) {
                    $level_price = $d['price'];
                }
                if ($quantity >= $d['num']) {
                    $price = $d['price'];
                }
            }
        }
        #如果没有匹配到折扣价格  查询是否为经销商 经销商享受一级折扣
        if (!$price) {
            $role = Customer::Where('id', $user_id)->value('role');
            #经销商享受一级折扣
            if ($role == 'distributor') {
                $price = $level_price;
            }
        }
        return $price;
    }

    /**
     * 获取适用的折扣价格
     * @param int   $quantity  购买数量
     * @param array $discounts 折扣规则数组
     * @return float 适用的折扣价格
     */
    function getApplicablePrice($quantity, $discounts) {
        // 按购买数量降序排列折扣规则
        usort($discounts, function($a, $b) {
            return $b['num'] <=> $a['num'];
        });

        // 寻找第一个满足条件的折扣
        foreach ($discounts as $discount) {
            if ($quantity >= $discount['num']) {
                return $discount['price'];
            }
        }

        // 如果没有满足的则返回第一个折扣（最低阶梯）
        return $discounts[count($discounts)-1]['price'];
    }

}
